package com.example.hilt_mvvm_http.base

import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.example.hilt_mvvm_http.one.model.BaseModel

import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch


open class BaseViewModel:ViewModel() {


    fun <M:BaseModel<T> , T>  execute(
        action: Flow<M>,
        onStart:(suspend ()->Unit)? = null,
        onError: (suspend (String) -> Unit)? = null,
        onFinished: (suspend (M) -> Unit)? = null,
    ) = viewModelScope.launch {
        action.onStart {//开始
            onStart?.invoke()
        }.catch {err->
            onError?.invoke(err.message.toString())
        }.collect{
            if(it.code == 0){
                onFinished?.invoke(it)
            }else{
                onError?.invoke(it.msg)
            }

        }
    }
}

/**
 * minState: Lifecycle.State = Lifecycle.State.STARTED,
 * 保证页面STARTED生命周期收集数据，页面销毁暂停取消收集
 */
inline fun <reified T> Flow<T>.observeWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    minState: Lifecycle.State = Lifecycle.State.STARTED,
    noinline action: suspend (T) -> Unit,
): Job = lifecycleOwner.lifecycleScope.launch {
    //collect 收集     collectLatest 收集最近的，解决背压
    flowWithLifecycle(lifecycleOwner.lifecycle, minState).collectLatest {
        action.invoke(it)
    }
}
